package com.woniuxy.course.service.impl;

import com.woniuxy.commons.dto.CourseDto;
import com.woniuxy.commons.entity.*;
import com.woniuxy.commons.exception.EtmsServiceException;
import com.woniuxy.commons.exception.course.ChapterInsertException;
import com.woniuxy.commons.exception.course.CourseAddException;
import com.woniuxy.commons.exception.course.CourseNotFoundException;
import com.woniuxy.commons.exception.course.TagInsertException;
import com.woniuxy.course.mapper.CourseChapterMapper;
import com.woniuxy.course.mapper.CourseMapper;
import com.woniuxy.course.mapper.CourseTagMapper;
import com.woniuxy.course.service.CourseService;
import com.woniuxy.course.utils.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Author LuoChen
 * @DateTime 2020-07-18 15:36:51
 * @Description 课程业务实现类
 */
@Service
public class CourseServiceImpl implements CourseService {

    @Autowired
    private CourseMapper courseMapper;
    @Autowired
    private CourseTagMapper courseTagMapper;
    @Autowired
    private CourseChapterMapper courseChapterMapper;

    /**
     * 查询所有课程
     *
     * @return: java.util.List<com.woniuxy.commons.dto.CourseDto>
     * @author: LuoChen
     * @dateTime: 2020-07-18 16:15:44
     */
    @Override
    public List<CourseDto> findAllCourses() {
        List<CourseDto> allCourses = null;
        try {
            allCourses = courseMapper.findAllCourses();
        } catch (Exception e) {
            throw new CourseNotFoundException("没找到任何课程", e);
        }
        return allCourses;
    }

    /**
     * 根据课程id查找课程
     *
     * @param cid
     * @return: com.woniuxy.commons.entity.Course
     * @author: LuoChen
     * @dateTime: 2020-07-18 16:16:09
     */
    @Override
    public Course findCourseByCid(int cid) {
        return courseMapper.findCourseByCid(cid);
    }

    /**
     * 根据条件分页查询课程信息
     *
     * @param condition
     * @return: java.util.List<com.woniuxy.commons.dto.CourseDto>
     * @author: LuoChen
     * @dateTime: 2020-07-18 16:16:13
     */
    @Override
    public PageBean<CourseDto> findCoursesByCondition(CourseDto condition) {
        int pageCode = condition.getIndex();
        int pageSize = condition.getPageSize();
        condition.setIndex((pageCode - 1) * pageSize);
        //查总数
        List<CourseDto> coursesByConditionNoPage = courseMapper.findCoursesByConditionNoPage(condition);
        int totalNums = coursesByConditionNoPage.size();
        //分页
        List<CourseDto> results = courseMapper.findCoursesByCondition(condition);
        //将得到的结果放入pageBean中
        PageBean<CourseDto> coursePageBean = new PageBean<>();
        coursePageBean.setPage(pageCode);
        coursePageBean.setPageSize(pageSize);
        coursePageBean.setData(results);
        coursePageBean.setTotalNum(totalNums);
        coursePageBean.setTotalPage(totalNums % pageSize == 0 ? totalNums / pageSize : totalNums / pageSize + 1);
        coursePageBean.setNumsOfCurrPage(pageCode != coursePageBean.getTotalPage() ? pageSize : totalNums % pageSize);
        return coursePageBean;
    }

    /**
     * 修改课程信息
     *
     * @param updatedInfo
     * @return: int
     * @author: LuoChen
     * @dateTime: 2020-07-18 16:16:16
     */
    @Override
    public int updateCourseInfo(Course updatedInfo) {
        return courseMapper.updateCourseInfo(updatedInfo);
    }

    /**
     * 新增一门课程
     *
     * @param course
     * @return: int
     * @author: LuoChen
     * @dateTime: 2020-07-18 16:16:19
     */
    @Override
    public int addCourse(Course course) {
        try {
            course.setPutMan(1);
            course.setExamId(0);
            course.setCover("http://117.51.156.132/images/"+course.getCover());
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String format = simpleDateFormat.format(new Date());
            course.setPutTime(format);
            course.setUpdateTime(format);
            //返回主键值
            int num = courseMapper.addCourse(course);
            if (!(num > 0)) {
                throw new CourseAddException("插入新课程数据失败");
            }
            int cid = course.getCid();
            System.out.println("cid : " + cid);
            List<String> tags = course.getCourseTags();
            List<CourseTag> courseTags = new ArrayList<>();
            for (int i = 0; i < tags.size(); i++) {
                CourseTag courseTag = new CourseTag().setCtname(tags.get(i));
                courseTags.add(courseTag);
            }
            //批量插入标签
            int numt = courseTagMapper.addCourseTags(courseTags);
            if (!(numt > 0)) {
                throw new TagInsertException("插入标签数据失败");
            }
            //更新中间表
            List<TagRelation> tagRelations = new ArrayList<>();
            for (CourseTag courseTag : courseTags) {
                TagRelation tagRelation = new TagRelation().setCid(cid).setCtid(courseTag.getCtid());
                tagRelations.add(tagRelation);
            }
            courseTagMapper.addRelation(tagRelations);
            //批量插入章节
            List<CourseChapter> courseChapters = course.getCourseChapters();
            for (int i = 0; i < courseChapters.size(); i++) {
                courseChapters.get(i).setCid(cid);
            }
            int numc = courseChapterMapper.addNewChapters(courseChapters);
            if (!(numc > 0)) {
                throw new ChapterInsertException("插入章节数据失败");
            }
            //批量插入课件章节映射
            for (CourseChapter courseChapter : courseChapters) {
                int cpid = courseChapter.getCpid();
                System.out.println("循环打印章节id:" + cpid);
                List<Integer> coursewares = courseChapter.getNewCwIds();
                List<CoursewareChapter> coursewareChapters = new ArrayList<>();
                for (int j = 0; j < coursewares.size(); j++) {
                    CoursewareChapter coursewareChapter = new CoursewareChapter()
                            .setCpid(cpid)
                            .setCwid(coursewares.get(j));
                    coursewareChapters.add(coursewareChapter);
                }
                courseChapterMapper.addRelation(coursewareChapters);
            }
            System.out.println(" ==== should be yes ====");
            return StatusCode.OPERATION_SUCCESS;
        } catch (EtmsServiceException e) {
            System.out.println(e.toString());
            e.printStackTrace();
            throw new EtmsServiceException("系统异常");
        }
    }

    /**
     * 查询所有教师
     *
     * @return: java.util.List<com.woniuxy.commons.entity.Teacher>
     * @author: LuoChen
     * @dateTime: 2020-08-03 15:30:09
     */
    @Override
    public List<Teacher> findAllTeachers() {
        return courseMapper.findAllTeachers();
    }

    /**
     * 下架一门课程
     *
     * @param cid
     * @return: int
     * @author: LuoChen
     * @dateTime: 2020-07-18 16:16:23
     */
    @Override
    public int courseOff(int cid) {
        return courseMapper.courseOff(cid);
    }

    /**
     * 上架/发布一门课程
     *
     * @param cid
     * @return: int
     * @author: LuoChen
     * @dateTime: 2020-07-18 16:16:27
     */
    @Override
    public int courseOn(int cid) {
        return courseMapper.courseOn(cid);
    }

    /**
     * 将一门课程暂时放入草稿箱
     *
     * @param cid
     * @return: int
     * @author: LuoChen
     * @dateTime: 2020-07-18 16:16:29
     */
    @Override
    public int putCourseIntoDraftsBox(int cid) {
        return courseMapper.putCourseIntoDraftsBox(cid);
    }

    /**
     * 删除一门课程，物理删除
     *
     * @param cid
     * @return: int
     * @author: LuoChen
     * @dateTime: 2020-07-18 16:16:35
     */
    @Override
    public int deleteCourseByCid(int cid) {
        return courseMapper.deleteCourseByCid(cid);
    }
}
